package com.cross.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.dom.DOMText;
import org.dom4j.io.XMLWriter;

import com.cross.core.AbstractWriter;
import com.cross.core.Header;
import com.cross.core.Item;
import com.cross.core.Row;

public class SimpleXmlWriter extends AbstractWriter {

	private Document document;
	private Element root;
	private XMLWriter writer;
	private int columnNum;

	public SimpleXmlWriter(Header header, File file) throws IOException {
		super.header = header;
		document = DocumentHelper.createDocument();
		root = DocumentHelper.createElement("cross");
		document.add(root);
		writer = new XMLWriter(new FileOutputStream(file));
	}
	
	public SimpleXmlWriter(Header header, OutputStream os) throws IOException {
		super.header = header;
		document = DocumentHelper.createDocument();
		root = DocumentHelper.createElement("cross");
		document.add(root);
		writer = new XMLWriter(os);
	}

	@Override
	protected void writeRow() {
		writeRowImpl();
	}

	private void writeRowImpl() {
		root.add(toElement(currentRow));
	}

	private Element toElement(Row row) {
		columnNum = 0;
		Element element = DocumentHelper.createElement("row");
		element.add(DocumentHelper.createAttribute(element, "objectName", header.getObjectName()));
		for(int i=0;i<row.getItems().size();i++){
			element.add(toElement(row.getItem(i)));
		}
		return element;
	}

	private Element toElement(Item item) {
		Element element = DocumentHelper.createElement(header.getColumn(columnNum++).getTitle());
		element.addAttribute("type", item.getType());
		element.add(new DOMText(item.getString()));
		return element;
	}

	@Override
	public void close() {
		try {
			writer.write(document);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
